//
//  MWTreeSeedController.m
//  XiRan-iOS
//
//  Created by liuyiming on 2019/12/4.
//  Copyright © 2019 Wood. All rights reserved.
//

#import "MWTreeSeedController.h"
#import "MWTreeSeedDetailsController.h"

#import "MWTreeSeedCell.h"

@interface MWTreeSeedController () <UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, strong) UITableView *tableView;

@property(nonatomic, strong) NSMutableArray *dataArray;

@property(nonatomic, assign) NSInteger page;
@property(nonatomic, assign) NSInteger size;
@property(nonatomic, assign) MWRequestMode requestMode;

@end

@implementation MWTreeSeedController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = [[MWConfigManager manager] objectForKey:@"treetype_info" defaultValue:@"树种介绍"];
    
    _page = 1;
    _size = 10;
    _requestMode = MWRequestModeRefresh;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.backgroundColor = MWHexColor(@"#F6F7FB");
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [self.view addSubview:_tableView];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
       
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
           make.edges.equalTo(self.view);
    }];
    
    MJRefreshNormalHeader *refreshHeader = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self refreshTreeSeede];
    }];
    refreshHeader.stateLabel.hidden = YES;
    _tableView.mj_header = refreshHeader;
    
    MJRefreshBackNormalFooter *refreshFooter = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreTreeSeed];
    }];
    refreshFooter.stateLabel.hidden = YES;
    _tableView.mj_footer.hidden = YES;
    _tableView.mj_footer = refreshFooter;
    
    [_tableView.mj_header beginRefreshing];
}

#pragma mark - 刷新数据
- (void)refreshTreeSeede {
    _page = 1;
    _requestMode = MWRequestModeRefresh;
    [self loadTreeSeedWithPage:_page size:_size];
}

#pragma mark - 加载更多数据
- (void)loadMoreTreeSeed {
    _page++;
    _requestMode = MWRequestModeLoadMore;
    [self loadTreeSeedWithPage:_page size:_size];
}

#pragma mark - 请求树种
- (void)loadTreeSeedWithPage:(NSInteger)page size:(NSInteger)size {
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
    [paraDic setObject:[MWUserManager manager].user.token forKey:@"token"];
    [paraDic setObject:[NSString stringWithFormat:@"%ld", page] forKey:@"page"];
    [paraDic setObject:[NSString stringWithFormat:@"%ld", size] forKey:@"size"];
    [paraDic setObject:[MWConfigManager manager].language forKey:@"language"];
    
    MWWeakSelf
    [[MWNetworkManager manager] POST:kTreeSeedListUrl parameters:paraDic progress:^(NSProgress *downloadProgress) {
        
    } success:^(id responseObject) {
        NSDictionary *dic = responseObject;
        NSInteger code = [[dic objectForKey:@"code"] integerValue];
//        NSString *msg = [dic objectForKey:@"msg"];
        
        if (code == 1) {
            NSDictionary *dataDic = [dic objectForKey:@"data"];
            NSArray *tempArray = [MWTreeSeed mj_objectArrayWithKeyValuesArray:dataDic];
            if (weakSelf.requestMode == MWRequestModeRefresh) {
                [weakSelf.tableView.mj_header endRefreshing];
                [self.dataArray removeAllObjects];
            } else {
                if (tempArray.count < weakSelf.size) {
                    [weakSelf.tableView.mj_footer endRefreshing];
                    
                } else {
                    [weakSelf.tableView.mj_footer endRefreshing];
                }
            }
            [self.dataArray addObjectsFromArray:tempArray];
            [weakSelf.tableView reloadData];
            
        } else {
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshing];
        }
    } failure:^(NSError *error) {
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
}

#pragma mark - UITableViewDataSource && UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if ([MWConfigManager manager].isNetError) {
        self.errorTitleLabel.text = [[MWConfigManager manager] objectForKey:@"click_retry" defaultValue:@"点击重试"];
        self.errorTitleLabel.hidden = self.errorImageView.hidden = NO;
        tableView.hidden = YES;
    } else if (!self.dataArray.count) {
        if (self.isFirst) {
            
        } else {
            self.errorTitleLabel.text = [[MWConfigManager manager] objectForKey:@"nodata" defaultValue:@"暂无数据"];
            self.errorTitleLabel.hidden = self.errorImageView.hidden = NO;
            tableView.hidden = YES;
        }
        
    } else {
        self.errorTitleLabel.hidden = self.errorImageView.hidden = YES;
        tableView.hidden = NO;
    }
    return self.dataArray.count;
}

- (void)refresh {
    [super refresh];
    [self.tableView.mj_header beginRefreshing];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 105;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 16.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 16)];
    headerView.backgroundColor = MWHexColor(@"#F6F7FB");
    return headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"MWTreeSeedCell";
    MWTreeSeedCell *treeSeedCell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!treeSeedCell) {
        treeSeedCell = [[MWTreeSeedCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        treeSeedCell.selectionStyle = UITableViewCellSelectionStyleNone;
        treeSeedCell.backgroundColor = MWHexColor(@"#F6F7FB");
    }
    
    [treeSeedCell setupData:self.dataArray[indexPath.section]];
    
    return treeSeedCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    MWTreeSeed *model =  self.dataArray[indexPath.section];
    MWTreeSeedDetailsController *controller = [[MWTreeSeedDetailsController alloc] init];
    controller.treeId = model.mid;
    [self.navigationController pushViewController:controller animated:YES];
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    
    return _dataArray;
}


@end
